package edu.nepu.flink.api.window;

import edu.nepu.flink.api.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SessionWindowTimeGapExtractor;
import org.apache.flink.streaming.api.windowing.time.Time;

/**
 * @Date 2024/2/29 22:34
 * @Created by chenshuaijun
 */
public class SessionWindow {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        SingleOutputStreamOperator<WaterSensor> source = env.socketTextStream("hadoop102", 9999).map(new MapFunction<String, WaterSensor>() {
            @Override
            public WaterSensor map(String value) throws Exception {
                String[] split = value.split(",");
                return new WaterSensor(split[0], Long.valueOf(split[1]), Integer.valueOf(split[2]));
            }
        });
        // 使用固定间隔时间的会话窗口
//        source.keyBy(WaterSensor::getId)
//                .window(ProcessingTimeSessionWindows.withGap(Time.seconds(10)))
//                .reduce(new ReduceFunction<WaterSensor>() {
//                    @Override
//                    public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
//                        return new WaterSensor(value1.id,value1.ts,value1.vc +value2.vc);
//                    }
//                }).print();
        // 我们还可以使用动态间隔时间的会话窗口，窗口的空闲间隔时间是由我么传入的参数进行控制的
        source.keyBy(WaterSensor::getId)
                        .window(ProcessingTimeSessionWindows.withDynamicGap(new SessionWindowTimeGapExtractor<WaterSensor>() {
                            /**
                             * 这个方法是从我们传入的参数中提取间隔的时间，每条数据到来的时候都会进行一次提取
                             * @param element The input element.
                             * @return
                             */
                            @Override
                            public long extract(WaterSensor element) {
                                // 单位是ms
                                return element.getTs() * 1000;
                            }
                        })).reduce(new ReduceFunction<WaterSensor>() {
                    @Override
                    public WaterSensor reduce(WaterSensor value1, WaterSensor value2) throws Exception {
                        return new WaterSensor(value1.id,value1.ts,value1.vc +value2.vc);
                    }
                }).print();
        env.execute();
    }
}
